package com.cjx.sec.web.interceptor;

import com.cjx.sec.pojo.doo.AuditLog;
import com.cjx.sec.repository.AuditLogRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 基于Interceptor的审计拦截器
 *
 * @author cjx
 * @date 2024/8/25 23:12
 */
@Slf4j
//@Component
public class AuditLogInterceptor extends HandlerInterceptorAdapter {
    
    
    @Resource
    private AuditLogRepository auditLogRepository;
    
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        
        log.info("*********3、审计*********");
        
        AuditLog auditLog = new AuditLog();
        auditLog.setHttpMethod(request.getMethod());
        auditLog.setPath(request.getRequestURI());
        
        auditLogRepository.save(auditLog);
        
        request.setAttribute("auditLogId", auditLog.getId());
        
        return true;
    }
    
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        Long auditLogId = (Long) request.getAttribute("auditLogId");
        
        AuditLog auditLog = auditLogRepository.findById(auditLogId).orElse(new AuditLog());
        auditLog.setHttpStatus(response.getStatus());
        
        auditLogRepository.save(auditLog);
        
    }
    
}
